package com.wwg.threadSort;

/**
 * @author: wwg
 * @date: 2022/3/11 11:03
 */


/**
 * wait控制线程顺序执行
 */
public class ThreadSortWait {

    private static Object myLock1 = new Object();
    private static Object myLock2 = new Object();

    /**
     * 为什么要加这两个标识状态?
     * 如果没有状态标识，当t1已经运行完了t2才运行，t2在等待t1唤醒导致t2永远处于等待状态
     */
    private static Boolean t1Run = false;
    private static Boolean t2Run = false;
    public static void main(String[] args) {

        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock1){
                    System.out.println(Thread.currentThread().getName() + "执行");
                    t1Run = true;
                    myLock1.notify();
                }
            }
        },"t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock1){
                    try {
                        if(!t1Run){
                            System.out.println("t2先休息会...");
                            myLock1.wait();
                        }
                        synchronized (myLock2){
                            System.out.println(Thread.currentThread().getName() + "执行");
                            t2Run = true;
                            myLock2.notify();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock2){
                    try {
                        if(!t2Run){
                            System.out.println("t3先休息会...");
                            myLock2.wait();
                        }
                        System.out.println(Thread.currentThread().getName() + "执行");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t3");

        thread2.start();
        thread1.start();
        thread3.start();
    }
}
